package com.flower8.controller;

import com.flower8.model.SysConfig;
import com.flower8.service.RedbagService;
import com.flower8.service.SysConfigService;
import com.flower8.service.UserService;
import com.flower8.sysconfig.constants.MsgConstants;
import com.flower8.utils.CreateRadomSeat;
import com.flower8.utils.PageData;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:  系统配置控制层
 * @Author: tanglin
 * @Date: 2019/11/18 14:13
 * @Version: 1.0
 */
@RestController
@RequestMapping("/sysconfig")
public class SysConfigController extends BaseController{
    private static final Logger log = LoggerFactory.getLogger(SysConfigController.class);

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private RedbagService redbagService;

    /**
     * 查询App首页展示模块列表
     * @param request
     * @return
     */
    @RequestMapping("/getHomeModelList")
    public Object getHomeModelList(HttpServletRequest request){
        logBefore(log, "++++++++++ 查询app首页展示模块列表 ++++++++++");
        PageData pd = new PageData(request);

        pd.put("start", Integer.parseInt( pd.get("start").toString() ) );
        pd.put("length", Integer.parseInt( pd.get("length").toString() ) );
        pd.put("type",1);

        Map res = new HashMap();
        try {
            List<SysConfig> sysConfigsList =  sysConfigService.getHomeModelList(pd);
            int total = sysConfigService.getHomeModelListCount(pd);
            res.put("data", sysConfigsList);
            res.put("recordsTotal", total);   //dataTable分页需要
            res.put("recordsFiltered", total);//dataTable分页需要
            res.put("draw", pd.get("draw").toString());//dataTable分页需要
            logAfter(log);
            Map<String, Object> dataMap = (Map<String, Object>) responseResultForSuccess(res);
            // 兼容旧网页
            dataMap.put("recordsTotal", total);   //dataTable分页需要
            dataMap.put("recordsFiltered", total);//dataTable分页需要
            dataMap.put("draw", pd.get("draw").toString());//dataTable分页需要
            return dataMap;
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError(MsgConstants.ERROR_99001_MSG);
        }
    }

    /**
     * 查询App个人中心展示模块列表
     * @param request
     * @return
     */
    @RequestMapping("/getMineModelList")
    public Object getMineModelList(HttpServletRequest request){
        logBefore(log, "++++++++++ 查询App个人中心展示模块列表 ++++++++++");
        PageData pd = new PageData(request);

        pd.put("start", Integer.parseInt( pd.get("start").toString() ) );
        pd.put("length", Integer.parseInt( pd.get("length").toString() ) );
        pd.put("type",2);

        Map res = new HashMap();
        try {
            List<SysConfig> sysConfigsList =  sysConfigService.getHomeModelList(pd);
            int total = sysConfigService.getHomeModelListCount(pd);
            res.put("data", sysConfigsList);
            res.put("recordsTotal", total);   //dataTable分页需要
            res.put("recordsFiltered", total);//dataTable分页需要
            res.put("draw", pd.get("draw").toString());//dataTable分页需要
            logAfter(log);
            Map<String, Object> dataMap = (Map<String, Object>) responseResultForSuccess(res);
            // 兼容旧网页
            dataMap.put("recordsTotal", total);   //dataTable分页需要
            dataMap.put("recordsFiltered", total);//dataTable分页需要
            dataMap.put("draw", pd.get("draw").toString());//dataTable分页需要
            return dataMap;
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError(MsgConstants.ERROR_99001_MSG);
        }
    }

    /**
     *  根据app首页展示模块的id查询
     * @param request
     * @return
     */
    @RequestMapping("/getHomeModelById")
    public Object getHomeModelById(HttpServletRequest request){
        logBefore(log, "++++++++++  根据app首页展示模块的id查询 ++++++++++");
        PageData pd = new PageData(request);

        try {
            SysConfig sysConfig =  sysConfigService.getHomeModelById(pd);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("homeMode", sysConfig);
            logAfter(log);
            return responseResultForSuccess(dataMap);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError(MsgConstants.ERROR_99001_MSG);
        }
    }

    /**
     * 更新/新增app首页展示模块
     * @param sysConfig
     * @return
     */
    @RequestMapping("/updateHomeModel")
    public Object updateHomeModel(@RequestBody SysConfig sysConfig){
        try {
            if(sysConfig.getId() != null){
                logBefore(log, "++++++++++ 更新app首页展示模块接口 ++++++++++");
                sysConfigService.updateHomeModel(sysConfig);
            }else{
                logBefore(log, "++++++++++ 新增app首页展示模块接口 ++++++++++");
                sysConfigService.addHomeModel(sysConfig);
            }

            logAfter(log);
            return responseResultForSuccess(null, "操作成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError("操作失败");
        }
    }

    /**
     * 删除app首页展示模块
     * @param id
     * @return
     */
    @RequestMapping("/deleteHomeModel")
    public Object deleteHomeModel(@RequestParam long id){
        logBefore(log, "++++++++++ 删除app首页展示模块 ++++++++++");
        try {
            sysConfigService.deleteHomeModel(id);
            logAfter(log);
            return responseResultForSuccess(null, "删除成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError("删除失败");
        }
    }


    /**
     * 红包重新排座
     * @return
     */
    @RequestMapping("/newRedPageSeat")
    public Object newRadomSeat(){
        logBefore(log, "++++++++++ 红包重新排座 ++++++++++");
        //生成新的红包排座
        List<Map> res = null;
        try {
            res = redbagService.getGoodsList(1L);
            List<String> RedPageList = CreateRadomSeat.radomRedPage(res);
            //清除原始的redis中的红包排座
            stringRedisTemplate.opsForList().trim("RedPageList",0,0);
            stringRedisTemplate.opsForList().leftPop("RedPageList");
            //存放新的红包排座
            stringRedisTemplate.opsForList().rightPushAll("RedPageList",RedPageList);
            logAfter(log);
            return responseResultForSuccess(null, "重置成功");
        } catch (Exception e) {
            e.printStackTrace();
            return responseResultForError("重置失败");
        }
    }

    /**
     * 大转盘重新排座
     * @return
     */
    @RequestMapping("/newBigWheelSeat")
    public Object newBigWheel(){
        logBefore(log, "++++++++++ 大转盘重新排座 ++++++++++");
        //生成新的大转盘排座
        try {
            sysConfigService.newBigWheel();
            return responseResultForSuccess(null, "重置成功");
        } catch (Exception e) {
            e.printStackTrace();
            return responseResultForError("重置失败");
        }
    }

    /**
     * 向奖池充值
     * @param totalMoney 充值金额
     * @return
     */
    @RequestMapping("/setRedPageMoney")
    public Object setRedPageMoney(@RequestParam String totalMoney,@RequestParam long uid){
        logBefore(log, "++++++++++ 向奖池充值 ++++++++++");

        try {
            //保存充值记录
            Map redbagLog = new HashMap();
            redbagLog.put("uid",uid);
            redbagLog.put("money",totalMoney);

            sysConfigService.addAwardMoneyRecord(redbagLog);
            logAfter(log);
            return responseResultForSuccess(null, "充值成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError("充值失败");
        }

    }

    /**
     * 获取红包池总金额
     * @return
     */
    @RequestMapping("/getTotalPoolMoney")
    public Object getTotalPoolMoney(){
        logBefore(log, "++++++++++ 获取红包池总金额 ++++++++++");
        Object obj = stringRedisTemplate.opsForValue().get("totalMoney");
        double money = 0;
        try {
            if(obj != null) {
                money = Double.parseDouble(stringRedisTemplate.opsForValue().get("totalMoney").toString());
            }else{//redis中奖池金额，从数据库中获取
                double redbgMoney =  sysConfigService.getAwardPool();
                money = redbgMoney;
                stringRedisTemplate.opsForValue().set("totalMoney",String.valueOf(redbgMoney));
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }

        logAfter(log);
        return money;
    }

    /**
     * 查询App数据字典配置列表
     * @param request
     * @return
     */
    @RequestMapping("/getAppDistList")
    public Object getAppDistList(HttpServletRequest request){
        logBefore(log, "++++++++++ 查询App数据字典配置列表 ++++++++++");
        PageData pd = new PageData(request);

        pd.put("start", Integer.parseInt( pd.get("start").toString() ) );
        pd.put("length", Integer.parseInt( pd.get("length").toString() ) );

        Map res = new HashMap();
        try {
            List<Map> sysConfigsList =  sysConfigService.getAppDist(pd);
            int total = sysConfigService.getAppDistCount(pd);
            res.put("data", sysConfigsList);
            res.put("recordsTotal", total);   //dataTable分页需要
            res.put("recordsFiltered", total);//dataTable分页需要
            res.put("draw", pd.get("draw").toString());//dataTable分页需要
            logAfter(log);
            Map<String, Object> dataMap = (Map<String, Object>) responseResultForSuccess(res);
            // 兼容旧网页
            dataMap.put("recordsTotal", total);   //dataTable分页需要
            dataMap.put("recordsFiltered", total);//dataTable分页需要
            dataMap.put("draw", pd.get("draw").toString());//dataTable分页需要
            return dataMap;
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError(MsgConstants.ERROR_99001_MSG);
        }
    }

    /**
     * 新增或修改App字典
     * @param request
     * @return
     */
    @RequestMapping("/addAppDict")
    public Object addAppDict(HttpServletRequest request){
       Map res = new HashMap();
        PageData pd = new PageData(request);
        try {
            //新增
            if(pd.getString("id") == null || "".equals(pd.getString("id"))){
                logBefore(log, "++++++++++ 新增App数据字典 ++++++++++");
                sysConfigService.addAppDict(pd);
            }else{
                logBefore(log, "++++++++++ 修改App数据字典 ++++++++++");
                sysConfigService.updAppDict(pd);
            }
            logAfter(log);
            return responseResultForSuccess(null, "操作成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError("操作失败");
        }
    }


    /**
     * 删除App字典数据
     * @param id
     * @return
     */
    @RequestMapping("/deleteAppDict")
    public Object deleteAppDict(@RequestParam Long id){
        Map res = new HashMap();
        try {
            //新增
            logBefore(log, "++++++++++ 删除App字典数据 ++++++++++");
            sysConfigService.deleteAppDict(id);
            logAfter(log);
            return responseResultForSuccess(null, "删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return responseResultForError("删除失败");
        }
    }


    /**
     * 查询配置的所有App内置模块
     * @return
     */
    @RequestMapping("/getAllSysConfig")
    public Object getAllSysConfig(){
        Map res = new HashMap();
        try {
            //新增
            logBefore(log, "++++++++++ 查询配置的所有App内置模块 ++++++++++");
            List<SysConfig> sysConfigsList =  sysConfigService.getHomeModelList(null);
            res.put("sysConfigsList",sysConfigsList);
            logAfter(log);
            return responseResultForSuccess(res);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError(MsgConstants.ERROR_99001_MSG);
        }
    }

    /**
     *
     * @return
     */
    @RequestMapping("/getAppDictById")
    public Object getAppDictById(@RequestParam Long id){
        Map res = new HashMap();
        try {
            logBefore(log, "++++++++++ 通过app字典的id查询 ++++++++++");
            Map resMap =  sysConfigService.getAppDictById(id);
            res.put("dict",resMap);
            logAfter(log);
            return responseResultForSuccess(res);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError(MsgConstants.ERROR_99001_MSG);
        }
    }

}
